package com.benmei.weike.web;

import com.benmei.weike.common.Constants;
import com.benmei.weike.exception.ClientException;
import com.benmei.weike.exception.ServerException;
import com.benmei.weike.util.JsonUtil;
import com.nativetalk.base.RetInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Peter on 2017/9/11.
 */
@RestController
public class ClientLogController {

    public static final Logger logger = LoggerFactory.getLogger(ClientLogController.class);

    @RequestMapping(value = "/clientLog", method = RequestMethod.POST)
    public RetInfo clientLog(@RequestBody String body) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(body));

            RetInfo retInfo = RetInfo.getSuccessInfo();
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ClientException e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getClientErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ServerException e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
